<?php 
namespace zeus\utils;

/**
 * 加解密
 */
// var_dump(Crypt::encode('123', 'fadf'));
// var_dump(Crypt::decode('an9PPQFFLLHtUgg=','fadf'));
class Crypt
{
	
	/**
	 * 加密方法。
	 *
	 * @param string $string
	 * @param string $key
	 * @param string $operation encode|decode
	 * @return string
	 */
	public static function encode($string, $key) 
	{
		$keyLength = strlen($key);
		$string = substr(md5($string . $key), 0, 8) . $string;
		$stringLength = strlen($string);
		$rndkey = $box = array();
		$result = '';

		for ($i = 0; $i <= 255; $i++) {
		    $rndkey[$i] = ord($key[$i % $keyLength]);
		    $box[$i] = $i;
		}

		for ($j = $i = 0; $i < 256; $i++) {
		    $j = ($j + $box[$i] + $rndkey[$i]) % 256;
		    $tmp = $box[$i];
		    $box[$i] = $box[$j];
		    $box[$j] = $tmp;
		}

		for ($a = $j = $i = 0; $i < $stringLength; $i++) {
		    $a = ($a + 1) % 256;
		    $j = ($j + $box[$a]) % 256;
		    $tmp = $box[$a];
		    $box[$a] = $box[$j];
		    $box[$j] = $tmp;
		    $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
		}
		return base64_encode($result);
	} 
	
	/**
	 * 加密，解密方法。
	 *
	 * @param string $string
	 * @param string $key
	 * @param string $operation encode|decode
	 * @return string
	 */
	public static function decode($string, $key) 
	{
		$keyLength = strlen($key);
		$string = base64_decode($string);
		$stringLength = strlen($string);
		$rndkey = $box = array();
		$result = '';

		for ($i = 0; $i <= 255; $i++) {
		    $rndkey[$i] = ord($key[$i % $keyLength]);
		    $box[$i] = $i;
		}

		for ($j = $i = 0; $i < 256; $i++) {
		    $j = ($j + $box[$i] + $rndkey[$i]) % 256;
		    $tmp = $box[$i];
		    $box[$i] = $box[$j];
		    $box[$j] = $tmp;
		}

		for ($a = $j = $i = 0; $i < $stringLength; $i++) {
		    $a = ($a + 1) % 256;
		    $j = ($j + $box[$a]) % 256;
		    $tmp = $box[$a];
		    $box[$a] = $box[$j];
		    $box[$j] = $tmp;
		    $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
		}
		if (substr($result, 0, 8) == substr(md5(substr($result, 8) . $key), 0, 8)) {
		    return substr($result, 8);
		} else {
		    return '';
		}
	}
}